﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using AirLinq.Expressions;
using AirLinq.Meta;

namespace AirLinq {
	public class AirLinqProvider : IQueryProvider{
		private readonly AirLinqDataContext _context;
		private readonly MetaType _metaType;
		internal AirLinqProvider(AirLinqDataContext context, MetaType metaType) {
			_context = context;
			_metaType = metaType;
		}
		public MetaType MetaType {
			get {
				return _metaType;
			}
		}
		public string GenerateQueryString(Expression expression) {
			using (var command = _context.DatabaseProvider.CreateCommand(_context.Connection, expression, this)) {
				return command.CommandText;
			}
		}
		#region IQueryProvider Members
		public IQueryable<TElement> CreateQuery<TElement>(Expression expression) {
			return new AirLinqQueryable<TElement>(expression, this);
		}
		public IQueryable CreateQuery(Expression expression) {
			throw new NotImplementedException();
		}

		public TResult Execute<TResult>(Expression expression) {
			var command=_context.DatabaseProvider.CreateCommand(_context.Connection, expression, this);
			var paramType=typeof(TResult);
			if (paramType.IsGenericType && paramType.GetGenericTypeDefinition().Equals(typeof(IEnumerator<>))) {
				var enumerableType=paramType.GetGenericArguments()[0];
				var factory = _context.CodeGenerator.GetReaderFactory(enumerableType);
				return (TResult) factory.Create(command);
			}
			throw new NotImplementedException();

		}
		public object Execute(Expression expression) {
			throw new NotImplementedException();
		}
		#endregion
	}
}
